package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.BlackList;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLike;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyCenterService {

    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0",check = false)
    private UserLikeApi userLikeApi;
    @Reference(version = "1.0.0",check = false)
    private VisitorsApi visitorsApi;
    @Autowired
    RecommendUserService recommendUserService;
    @Autowired
    private  IMService imService;
    @Autowired
    private TanHuaService tanHuaService;
    @Autowired
    private SettingsService settingsService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private BlackListService blackListService;

    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.getuser().getId();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().getValue() ==1? "man" : "woman");
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        User user = UserThreadLocal.getuser();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StringUtils.replaceAll(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoService.updateUserInfoByUserId(userInfo);
    }

    public CountsVo queryCounts() {
        Long id = UserThreadLocal.getuser().getId();
        CountsVo countsVo = new CountsVo();

        countsVo.setEachLoveCount(userLikeApi.queryMutualLikeCount(id));
        countsVo.setFanCount(userLikeApi.queryFanCount(id));
        countsVo.setLoveCount(userLikeApi.queryLikeCount(id));

        return countsVo;
    }

    public PageResult queryLikeList(Integer valueOf, Integer page, Integer pageSize, String nickname) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        Long id = UserThreadLocal.getuser().getId();
        List<Object> userIdList = null;
        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (valueOf){
            case 1 :{
                PageInfo<UserLike> userLikePageInfo = userLikeApi.queryMutualLikeList(id, page, pageSize);
                userIdList= CollUtil.getFieldValues(userLikePageInfo.getRecords(), "userId");
                break;}
            case 2 :{
                PageInfo<UserLike> userLikePageInfo = userLikeApi.queryLikeList(id, page, pageSize);
                userIdList= CollUtil.getFieldValues(userLikePageInfo.getRecords(), "likeUserId");
                break;}
            case 3 :{
                PageInfo<UserLike> userLikePageInfo = userLikeApi.queryFanList(id, page, pageSize);
                userIdList= CollUtil.getFieldValues(userLikePageInfo.getRecords(), "userId");
                break;}
            case 4 :{
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(id, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId");break;}
            default:
                return pageResult;
        }
        if(CollUtil.isEmpty(userIdList))
            return pageResult;
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIdList);

        if(StrUtil.isNotEmpty(nickname))
            queryWrapper.like("nick_name", nickname);
        List<UserInfo> userInfos = userInfoService.queryUserInfoList(queryWrapper);
        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (Object A:userIdList) {
            for (UserInfo userInfo : userInfos) {
                if(Long.valueOf(A.toString())==userInfo.getUserId()) {
                    UserLikeListVo userLikeListVo = new UserLikeListVo();
                    userLikeListVo.setAge(userInfo.getAge());
                    userLikeListVo.setAvatar(userInfo.getLogo());
                    userLikeListVo.setCity(userInfo.getCity());
                    userLikeListVo.setEducation(userInfo.getEdu());
                    userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
                    userLikeListVo.setId(userInfo.getUserId());
                    userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
                    userLikeListVo.setNickname(userInfo.getNickName());
                    //是否喜欢  userLikeApi中的isLike开放出来
                    userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(id, userInfo.getUserId()));


                    Double score = this.recommendUserService.queryScore(id, userInfo.getUserId());
                    userLikeListVo.setMatchRate(Convert.toInt(score));

                    userLikeListVos.add(userLikeListVo);
                    break;
                }
            }
        }
        pageResult.setItems(userLikeListVos);
        return pageResult;


    }
    /**
     * 取消喜欢
     *
     * @param userId
     */
    public void disLike(Long userId) {
        //判断当前用户与此用户是否相互喜欢
        User user = UserThreadLocal.getuser();
        Boolean mutualLike = this.userLikeApi.isMutualLike(user.getId(), userId);

        //取消喜欢
        this.userLikeApi.notLikeUser(user.getId(), userId);

        if(mutualLike){
            //取消好友关系，解除在环信平台的好友关系
            this.imService.removeUser(userId);
        }
    }

    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        boolean b = tanHuaService.likeUser(userId);
    }

    public SettingsVo querySettings() {
        SettingsVo settingsVo = new SettingsVo();
        User user = UserThreadLocal.getuser();

        //设置用户的基本信息
        settingsVo.setId(user.getId());
        settingsVo.setPhone(user.getMobile());

        //查询用户的配置数据
        Settings settings = this.settingsService.querySettings(user.getId());
        if(ObjectUtil.isNotEmpty(settings)){
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }

        //查询陌生人问题
        settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(user.getId()));
        return settingsVo;
    }

    public void saveQuestions(String content) {
        User user = UserThreadLocal.getuser();
        this.questionService.save(user.getId(), content);
    }

    public PageResult queryBlacklist(Integer page, Integer pagesize) {
        User user = UserThreadLocal.getuser();
        IPage<BlackList> blackListIPage = blackListService.queryBlacklist(user.getId(),page,pagesize);
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        if(CollUtil.isEmpty(blackListIPage.getRecords()))
            return pageResult;
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));
        List<Object> blackUserId = CollUtil.getFieldValues(blackListIPage.getRecords(), "blackUserId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(blackUserId);
        ArrayList<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVos.add(blackListVo);
        }
        pageResult.setItems(blackListVos);
        return pageResult;
    }

    public void delBlacklist(Long userId) {

        User user = UserThreadLocal.getuser();
        this.blackListService.delBlacklist(user.getId(), userId);
    }

    public void updateNotification(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        Long id = UserThreadLocal.getuser().getId();
        Boolean a=settingsService.updateNotification(id,likeNotification,pinglunNotification,gonggaoNotification);

    }


}